import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/components/Loading/fullScreen";
import { LOGIN_URL } from "@/config";
import { ElMessage } from "element-plus";
import { ResultData } from "@/api/types";
import { ResultEnum } from "@/enums/httpEnum";
import { AxiosCanceler } from "../helper/axiosCancel";
import { useUserStore } from "@/stores/modules/user";
import { secProcess } from "./security";
import router from "@/routers";
import { relogin } from "@/components/application/reLogin/index";
import { useBrowserLocation } from "@vueuse/core";
const location = useBrowserLocation();
export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  loading?: boolean;
  cancel?: boolean;
}

const config = {
  // 默认地址请求地址，可在 .env.** 文件中修改
  baseURL: import.meta.env.VITE_API_URL as string,
  // 设置超时时间
  timeout: ResultEnum.TIMEOUT as number,
  // 跨域时候允许携带凭证
  withCredentials: true
};

const axiosCanceler = new AxiosCanceler();

class RequestHttp {
  service: AxiosInstance;
  public constructor(config: AxiosRequestConfig) {
    // instantiation
    this.service = axios.create(config);

    /**
     * @description 请求拦截器
     * 客户端发送请求 -> [请求拦截器] -> 服务器
     * token校验(JWT) : 接受服务器返回的 token,存储到 vuex/pinia/本地储存当中
     */
    this.service.interceptors.request.use(
      (config: CustomAxiosRequestConfig) => {
        const userStore = useUserStore();
        // 重复请求不需要取消，在 api 服务中通过指定的第三个参数: { cancel: false } 来控制
        config.cancel ?? (config.cancel = true);
        config.cancel && axiosCanceler.addPending(config);
        // 当前请求不需要显示 loading，在 api 服务中通过指定的第三个参数: { loading: false } 来控制
        config.loading ?? (config.loading = true);
        config.loading && showFullScreenLoading();
        if (config.headers && typeof config.headers.set === "function") {
          config.headers.set("x-access-token", userStore.token);
        }
        // 安全处理
        if (config.headers && config.headers.CM) {
          secProcess(config, false);
        } else {
          secProcess(config, true);
        }
        return config;
      },
      (error: AxiosError) => {
        return Promise.reject(error);
      }
    );

    /**
     * @description 响应拦截器
     *  服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
     */
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const { data, config } = response;
        const userStore = useUserStore();
        axiosCanceler.removePending(config);
        tryHideFullScreenLoading();
        // 登录失效
        if (data.code == ResultEnum.Unauthorized) {
          userStore.setToken("");
          router.replace(LOGIN_URL);
          return refeshToken(response);
        }
        // 全局错误信息拦截（防止下载文件的时候返回数据流，没有 code 直接报错）
        if (data.code && data.code !== ResultEnum.SUCCESS) {
          return Promise.reject(data);
        }
        // 成功请求（在页面上除非特殊情况，否则不用处理失败逻辑）
        return data;
      },
      async (error: AxiosError) => {
        const { response } = error;
        tryHideFullScreenLoading();
        // 根据服务器响应的错误状态码，做不同的处理
        if (response && response.status === ResultEnum.Unauthorized) {
          return refeshToken(response);
        } else {
          if (response) checkStatus(response.status);
          // 请求超时 && 网络错误单独判断，没有 response
          if (error.message.indexOf("timeout") !== -1) ElMessage.error("请求超时！请您稍后重试");
          if (error.message.indexOf("Network Error") !== -1) ElMessage.error("网络错误！请您稍后重试");
          // 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
          // 修复：区分本地开发环境和生产环境的网络状态检测
          if (!window.navigator.onLine) {
            // 检查是否为本地开发环境（localhost或127.0.0.1）
            const isLocalhost = window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1";
            // 检查是否为本地开发环境的API代理地址
            const isLocalApi = import.meta.env.VITE_API_URL === "/api";

            // 只有在非本地环境且确实没有网络时才跳转到500页面
            if (!(isLocalhost && isLocalApi)) {
              router.replace("/500");
            }
          }
          return Promise.reject(error);
        }
      }
    );
  }

  /**
   * @description 常用请求方法封装
   */
  get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.get(url, { params, ..._object });
  }
  post<T>(url: string, params?: object | string, _object = {}): Promise<ResultData<T>> {
    return this.service.post(url, params, _object);
  }
  put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.put(url, params, _object);
  }
  delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
    return this.service.delete(url, { params, ..._object });
  }
  download(url: string, params?: object, _object = {}): Promise<BlobPart> {
    return this.service.get(url, { params, ..._object, responseType: "blob" });
  }
  postDownload(url: string, params?: object, _object = {}): Promise<BlobPart> {
    return this.service.post(url, params, { ..._object, responseType: "blob" });
  }
  downloadUrl = () => {
    let browserUrl = import.meta.env.VITE_API_URL;
    if (browserUrl && browserUrl.indexOf("http") == -1) {
      browserUrl = location.value.origin + import.meta.env.VITE_API_URL + "/file/";
    } else {
      browserUrl = browserUrl + "/file/";
    }
    return browserUrl;
  };
}

const checkStatus = (status: number) => {
  switch (status) {
    case 400:
      ElMessage.error("请求失败！请您稍后重试");
      break;
    case 401:
      ElMessage.error("登录失效！请您重新登录");
      break;
    case 403:
      ElMessage.error("当前账号无权限访问！");
      break;
    case 404:
      ElMessage.error("你所访问的资源不存在！");
      break;
    case 405:
      ElMessage.error("请求方式错误！请您稍后重试");
      break;
    case 408:
      ElMessage.error("请求超时！请您稍后重试");
      break;
    case 500:
      ElMessage.error("服务异常！");
      break;
    case 502:
      ElMessage.error("网关错误！");
      break;
    case 503:
      ElMessage.error("服务不可用！");
      break;
    case 504:
      ElMessage.error("网关超时！");
      break;
    default:
      ElMessage.error("请求失败！");
  }
};

// 避免其他接口同时请求(只请求一次token接口)
let isRefreshToken = false;
const refeshToken = response => {
  if (!isRefreshToken) {
    isRefreshToken = true;
    relogin().then(() => {
      isRefreshToken = false;
      // 发布 消息
      retryOldRequest.trigger();
    });
  }
  // 收集订阅者 并把成功后的数据返回原接口
  return retryOldRequest.listen(response);
};

const retryOldRequest = {
  // 维护失败请求的response
  requestQuery: <any>[],

  // 添加订阅者
  listen(response) {
    return new Promise(resolve => {
      this.requestQuery.push(() => {
        const userStore = useUserStore();
        let config = response.config || {};
        config.headers.Authorization = userStore.token;
        resolve(httpRequest.service(config));
      });
    });
  },

  // 发布消息
  trigger() {
    this.requestQuery.forEach(fn => {
      fn();
    });
    this.requestQuery = [];
  }
};

const httpRequest = new RequestHttp(config);
export default httpRequest;
